package com.monkeygroup.mygoplus.view.home.activity.sell;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.base.BaseActivity;
import com.monkeygroup.mygoplus.commit.thing.vo.PropertyCommitVO;
import com.monkeygroup.mygoplus.common.utils.LocalInfo;
import com.monkeygroup.mygoplus.common.utils.StringUtil;
import com.monkeygroup.mygoplus.http.PersonHttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.monkeygroup.mygoplus.http.ThingsHttpModel;
import com.monkeygroup.mygoplus.thing.vo.MyImageVO;
import com.monkeygroup.mygoplus.thing.vo.RentVO;
import com.monkeygroup.mygoplus.thing.vo.UserVO;
import com.monkeygroup.mygoplus.view.home.activity.ThingsDetailActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by cumt on 2017/6/9.
 */

public class ThingsLandDetailActivity extends BaseActivity implements OnMapReadyCallback {

    public static void gotoActivity(Activity activity, String type, String parent, String modal, String carport) {

        Intent intent = new Intent(activity,
                ThingsLandDetailActivity.class);

        Bundle bundle = new Bundle();
        bundle.putSerializable("param", "");
        intent.putExtra("param", bundle);

        //1-租房，2-出售
        intent.putExtra("type", type);
        intent.putExtra("parent", parent);
        //
        intent.putExtra("modal", modal);
        intent.putExtra("carport", carport);

        activity.startActivityForResult(intent, 3);
    }

    private LayoutInflater mInflater;

    private TextView txt_top,txtTitle, txtImgSize, txtPurpose, txtName, txtContact, txtAddr, txtSalePriceTitle,
            txtSaleprice,txtArea, txtAreaTitlie, txtAre, txtTypeTitle, txtType,txt_shopequip_noe,txt_shopequip_two;

    private HorizontalScrollView scrollView;
    private LinearLayout linear;

    private LinearLayout layout_shortcut;
    private List<MyImageVO> imageVO;
    private RentVO rentVO;
    //請求
    private ThingsHttpModel httpThingsModel,httpThingsModel1;

    private ViewPager viewPager;
    private ImageView[] mImageViews;
    ImageLoader loader;
    DisplayImageOptions options;

    private String type,parent,modal,carpot;

    private RentVO propertyModel;

    //請求參數
    private Map<String, String> params;
    private PersonHttpModel personHttpModel;
    private StringBuffer url;
    private  PropertyCommitVO vo = null;

    @Override
    public void setContentView() {
        mInflater = LayoutInflater.from(this);
        setContentView(R.layout.activity_sell_land_detail);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void initView() {

//        layout_shortcut= (LinearLayout) findViewById(R.id.layout_shortcut);
//        layout_shortcut.setVisibility(View.INVISIBLE);
        txtTitle = (TextView) findViewById(R.id.txt_title);
        txtTitle.setText("出售物件");
        txt_top = (TextView) findViewById(R.id.txt_top);
        txt_top.setText("发布");

        txtImgSize = (TextView) findViewById(R.id.viewPager_things_all);
        txtPurpose = (TextView) findViewById(R.id.text_things_detail_purpose);
        txtName = (TextView) findViewById(R.id.text_things_detail_name);
        txtContact = (TextView) findViewById(R.id.text_detail_contact);
        txtAddr = (TextView) findViewById(R.id.text_detail_addr);
        txtSalePriceTitle = (TextView) findViewById(R.id.text_things_detail_saleprice_title);
        txtSaleprice = (TextView) findViewById(R.id.text_things_detail_saleprice);
        txtAreaTitlie = (TextView) findViewById(R.id.text_things_detail_area_title);
        txtArea = (TextView) findViewById(R.id.text_things_detail_area);

        txtTypeTitle = (TextView) findViewById(R.id.text_things_detail_type_title);
        txtType = (TextView) findViewById(R.id.text_things_detail_type);
        txt_shopequip_noe= (TextView) findViewById(R.id.txt_shopequip_noe);
        txt_shopequip_two= (TextView) findViewById(R.id.txt_shopequip_two);

        scrollView = (HorizontalScrollView) this.findViewById(R.id.horizontal_scrollView_things);
        linear = (LinearLayout) this.findViewById(R.id.linearlayout_things_scrollView);


        Intent intent = this.getIntent();
        Bundle bundle =  intent.getExtras();
        type = bundle.getString("type");
        parent= bundle.getString("parent");
        modal= bundle.getString("modal");
        carpot= bundle.getString("carpot");



        String param = (String) getIntent().getBundleExtra("param").getSerializable("param");

        String param1="";
        if(StringUtil.isBlank(param)){

            url=new StringBuffer(RequestUrl.savepropertyUrl);
            propertyModel = new RentVO();
            propertyModel.setLat(0);
            propertyModel.setLng(0);

            if("2".equals(type)){

                //土地
                if("6".equals(parent)){
                    vo=LocalInfo.getLandProperty(ThingsLandDetailActivity.this,modal);
                    vo.setProperty_sale(1);
                }

            }
            else if("1".equals(type)){
                vo=LocalInfo.getRentLandProperty(ThingsLandDetailActivity.this,modal);
                vo.setProperty_rent(1);
            }
            String imgtype="";
            //圖片
            if(vo.getPropertyimg_sceimgtype()!=null){
                for(int i=0;i<vo.getPropertyimg_sceimgtype().length;i++){
//                Log.e("getPropertyie==",""+vo.getPropertyimg_sceimgtype()[i]);
                    if(!StringUtil.isBlank(vo.getPropertyimg_sceimgtype()[i])){
                        imgtype=vo.getPropertyimg_sceimgtype()[i];
                    }
                }
                if(vo.getPropertyimg_path1()!=null){

                    for(int i=0;i<vo.getPropertyimg_path1().length;i++) {
                        if (!StringUtil.isBlank(vo.getPropertyimg_path1()[i])) {
                            if(i==0){
                                url.append("?propertyimg_sceimgtype[]="+imgtype);
                            }
                            else{
                                url.append("&propertyimg_sceimgtype[]="+imgtype);
                            }

                            url.append("&propertyimg_path1[]="+vo.getPropertyimg_path1()[i]);
                            url.append("&propertyimg_path3[]="+vo.getPropertyimg_path1()[i]);
                            url.append("&propertyimg_path4[]="+vo.getPropertyimg_path1()[i]);
                            url.append("&propertyimg_width[]="+vo.getPropertyimg_width()[i]);
                            url.append("&propertyimg_height[]="+vo.getPropertyimg_height()[i]);
                            url.append("&propertyimg_size[]="+vo.getPropertyimg_size()[i]);
                            url.append("&propertyimg_name[]="+vo.getPropertyimg_name()[i]);

                        }
                    }
                }

                for(int i=0;i<vo.getPropertyimg_sceimgtype().length;i++) {
                    if (!StringUtil.isBlank(vo.getPropertyimg_sceimgtype()[i])) {



                    }
                }
            }
            Log.e("modalmodal==",""+parent+"=="+modal+"::"+vo);
            getThingsInfo(vo);

            params = new HashMap<String, String>();
            vo.toMap(params);
            txt_top.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                    personHttpModel.requestUserLogin();
                }
            });
            param = "?area="+String.valueOf(vo.getProperty_area())+"&modal="+vo.getProperty_modal();
        }
        else{
            initDetailRequest(param);
            httpThingsModel.requestThings();
            param1 = "?area="+propertyModel.getArea()+"&modal="+propertyModel.getModal();
        }


        initHorizontalScrollViewRequest(param1);
        httpThingsModel1.requestThings();
    }

    @Override
    public void setListener() {

    }

    @Override
    public void doEvent() {

    }

    public void initHorizontalScrollViewRequest(String param) {
        httpThingsModel1 = new ThingsHttpModel(RequestUrl.thingsbuyUrl + param,
                new ThingsHttpModel.SimpleOnHttpRequestListener() {
                    @Override
                    public void onRequestFinished(String resultCode, Integer timestamp) {

                    }

                    @Override
                    public void onRequestFinished(String resultCode, Object property, Object user, Object users, Object circuit, Object img) {
                        Gson gson = new Gson();
                        List<RentVO> propertys = gson.fromJson(gson.toJson(property), new TypeToken<List<RentVO>>() {
                        }.getType());

                        for (int i = 0; i < propertys.size(); i++) {
                            if(propertys.get(i).getSeq()==propertyModel.getSeq()){
                                continue;
                            }
                            createChildLinearLayout(propertys.get(i),i);
                        }

                    }

                    @Override
                    public void onBuildingRequestFinished(String resultCode, Object building, Object user, Object users, Object circuit, Object img) {

                    }

                    @Override
                    public void onCommunityRequestFinished(String resultCode, Object community, Object user, Object users, Object circuit, Object img) {

                    }
                }, true);

        personHttpModel = new PersonHttpModel(url.toString(),params,new PersonHttpModel.SimpleOnHttpRequestListener(){


            @Override
            public void onRequestFinished(String resultCode, Integer timestamp) {

            }

            @Override
            public void onRequestFinished(String resultCode, int seq, int isbind, String acc) {


            }

            @Override
            public void onRequestFinished(String resultCode, int seq, int flag, String flag_name, int secflag, String secflag_name) {

                Log.e("resultCoderesultCode===",""+"ERROR_OK".equals(resultCode));
                //請求成功
                if("ERROR_OK".equals(resultCode)){
                    Toast.makeText(ThingsLandDetailActivity.this, "发布成功",
                            Toast.LENGTH_SHORT).show();
                    txt_top.setVisibility(View.INVISIBLE);
                    LocalInfo.removeProperty(ThingsLandDetailActivity.this,vo);

                }
                else{

                    Toast.makeText(ThingsLandDetailActivity.this, "发布失败",
                            Toast.LENGTH_SHORT).show();
                }
            }

        },true);
    }

    public void initDetailRequest(String param) {
        httpThingsModel = new ThingsHttpModel(RequestUrl.getPropertyUrl + param,
                new ThingsHttpModel.SimpleOnHttpRequestListener() {
                    @Override
                    public void onRequestFinished(String resultCode, Integer timestamp) {

                    }

                    @Override
                    public void onRequestFinished(String resultCode, Object property, Object user, Object users, Object circuit, Object img) {
                        Gson gson = new Gson();
                        List<MyImageVO> imgModel = gson.fromJson(gson.toJson(img), new TypeToken<List<MyImageVO>>() {
                        }.getType());
                         propertyModel = gson.fromJson(gson.toJson(property), new TypeToken<RentVO>() {
                        }.getType());
                        UserVO userVO = gson.fromJson(gson.toJson(user), new TypeToken<UserVO>() {
                        }.getType());
                        setImage(imgModel);
                        setThingsInfo(propertyModel);
                        setUserInfo(userVO);
                    }

                    @Override
                    public void onBuildingRequestFinished(String resultCode, Object building, Object user, Object users, Object circuit, Object img) {

                    }

                    @Override
                    public void onCommunityRequestFinished(String resultCode, Object community, Object user, Object users, Object circuit, Object img) {

                    }
                }, true);
    }

    private void setImage(List<MyImageVO> imgModel) {
        loader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.mipmap.img_mygoempty_nor3x)
                .showImageOnFail(R.mipmap.img_mygoempty_nor3x).cacheInMemory(true)
                .cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(0))
                .build();
        List<String> imgs = new ArrayList<>();
        for (MyImageVO vo : imgModel) {
            if (vo.getCover() != 1) {
                imgs.add(vo.getPath3());
            }
        }
        viewPager = (ViewPager) findViewById(R.id.viewPager_things_all_img);
        mImageViews = new ImageView[imgs.size()];
        for (int i = 0; i < imgs.size(); i++) {
            final ImageView imageView = new ImageView(this);
            mImageViews[i] = imageView;

            loader.displayImage(imgs.get(i), imageView, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {
                    imageView.setImageResource(R.mipmap.img_mygoempty_nor3x);
                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {
                    imageView.setImageResource(R.mipmap.img_mygoempty_nor3x);
                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }
            });
        }

        viewPager.setAdapter(new ThingsLandDetailActivity.MyAdapter());
        txtImgSize.setText(1 + "/" + mImageViews.length);
        viewPager.setCurrentItem(0);
        viewpagerListener();
        //设置ViewPager的默认项, 设置为长度的100倍，这样子开始就能往左滑动  
        //viewPager.setCurrentItem((mImageViews.length)*100);
    }

    private void viewpagerListener() {
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                txtImgSize.setText((arg0 + 1) + "/" + mImageViews.length);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mImageViews.length;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager) container).removeView(mImageViews[position % mImageViews.length]);
        }

        /**
         * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
         */
        @Override
        public Object instantiateItem(View container, int position) {
            ((ViewPager) container).addView(mImageViews[position % mImageViews.length], 0);
            return mImageViews[position % mImageViews.length];
        }

    }

    private void setThingsInfo(RentVO propertyModel) {
        txtPurpose.setText(propertyModel.getPurpose());
        txtName.setText(propertyModel.getName());
        txtAddr.setText(propertyModel.getAddr());
        txtSalePriceTitle.setText("售價");
        txtSaleprice.setText(propertyModel.getSaleprice() + " 萬");
        txtAreaTitlie.setText("坪數");
        txtArea.setText(propertyModel.getLawnarea() + " 坪");
        txtType.setText(propertyModel.getPurpose());


    }

    private void getThingsInfo(PropertyCommitVO propertyModel) {

        txtPurpose.setText(propertyModel.getProperty_purpose());
        txtName.setText(propertyModel.getProperty_name());
//        txtAddr.setText(propertyModel.getProperty());
        txtSalePriceTitle.setText("售價");
        txtSaleprice.setText(propertyModel.getProperty_saleprice() + " 萬");
        txtAreaTitlie.setText("坪數");
        txtArea.setText(propertyModel.getProperty_ownershiparea() + " 坪");

        Log.e("propertyMtyoor()==",""+propertyModel.getProperty_minfloor());

        txtType.setText(propertyModel.getProperty_purpose());
        txt_shopequip_noe.setText(   fillEquip(propertyModel.getProperty_landapplication()).toString());
        txt_shopequip_two.setText(fillattribute(propertyModel.getProperty_landattribute()).toString());


    }

    private void setUserInfo(UserVO userVO) {
        txtContact.setText(userVO.getName() + " " + userVO.getTel());
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        LatLng positon = new LatLng(25.04094, 121.45502);
        googleMap.addMarker(new MarkerOptions().position(positon).title(""));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(positon));
        GoogleMapOptions options = new GoogleMapOptions().liteMode(true);

    }

    private StringBuffer fillattribute(String property_equipment){

        String[] equipment = property_equipment.split(",");
        StringBuffer text = new StringBuffer("");
        for (int i = 0; i < equipment.length; i++) {
            if (!"".equals(equipment[i])) {

                if ("1".equals(equipment[i])) {
                    text.append("住宅區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }

                } else if ("2".equals(equipment[i])) {
                    text.append("商業區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
                else if ("3".equals(equipment[i])) {
                    text.append("工業用地");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
                else if ("4".equals(equipment[i])) {
                    text.append("文教區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
                else if ("5".equals(equipment[i])) {
                    text.append("風景區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
                else if ("6".equals(equipment[i])) {
                    text.append("保護區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
                else if ("7".equals(equipment[i])) {
                    text.append("行政區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
                else if ("8".equals(equipment[i])) {
                    text.append("特定農業區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
                else if ("9".equals(equipment[i])) {
                    text.append("一般農業區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
                else if ("10".equals(equipment[i])) {
                    text.append("鄉村區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
                else if ("11".equals(equipment[i])) {
                    text.append("森林區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
                else if ("12".equals(equipment[i])) {
                    text.append("山坡地保育區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
                else if ("13".equals(equipment[i])) {
                    text.append("公園區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
                else if ("14".equals(equipment[i])) {
                    text.append("河川區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
                else if ("15".equals(equipment[i])) {
                    text.append("其他或專用區");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }

            }

        }

        return text;
    }
    private StringBuffer fillEquip(String property_equipment) {
        String[] equipment = property_equipment.split(",");
        StringBuffer text = new StringBuffer("");
        for (int i = 0; i < equipment.length; i++) {
            if (!"".equals(equipment[i])) {
                if ("1".equals(equipment[i])) {
                    text.append("甲種建築用地");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }

                } else if ("2".equals(equipment[i])) {
                    text.append("乙種建築用地");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                } else if ("3".equals(equipment[i])) {
                    text.append("丙種建築用地");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                } else if ("4".equals(equipment[i])) {
                    text.append("丁種建築用地");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                } else if ("5".equals(equipment[i])) {
                    text.append("農牧用地");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                } else if ("6".equals(equipment[i])) {
                    text.append("養殖用地");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                } else if ("7".equals(equipment[i])) {
                    text.append("遊憩用地");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                } else if ("8".equals(equipment[i])) {
                    text.append("墳墓用地");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                } else if ("9".equals(equipment[i])) {
                    text.append("鹽業用地");
                    if (i != equipment.length - 1) {
                        text.append(",");
                    }
                }
            } else if ("10".equals(equipment[i])) {
                text.append("鹽業用地");
                if (i != equipment.length - 1) {
                    text.append(",");
                }

            } else if ("11".equals(equipment[i])) {
                text.append("林業用地");
                if (i != equipment.length - 1) {
                    text.append(",");
                }

            } else if ("12".equals(equipment[i])) {
                text.append("礦業用地");
                if (i != equipment.length - 1) {
                    text.append(",");
                }

            } else if ("13".equals(equipment[i])) {
                text.append("窯業用地");
                if (i != equipment.length - 1) {
                    text.append(",");
                }

            } else if ("14".equals(equipment[i])) {
                text.append("交通用地");
                if (i != equipment.length - 1) {
                    text.append(",");
                }
            }
            else if ("15".equals(equipment[i])) {
                text.append("水利用地");
                if (i != equipment.length - 1) {
                    text.append(",");
                }
            }
            else if ("16".equals(equipment[i])) {
                text.append("古跡保存用地");
                if (i != equipment.length - 1) {
                    text.append(",");
                }
            }
            else if ("17".equals(equipment[i])) {
                text.append("生態保護用地");
                if (i != equipment.length - 1) {
                    text.append(",");
                }
            }
            else if ("18".equals(equipment[i])) {
                text.append("國土保安用地");
                if (i != equipment.length - 1) {
                    text.append(",");
                }
            }
            else if ("19".equals(equipment[i])) {
                text.append("特定目的事業用地");
                if (i != equipment.length - 1) {
                    text.append(",");
                }
            }
            else if ("20".equals(equipment[i])) {
                text.append("其他");
                if (i != equipment.length - 1) {
                    text.append(",");
                }
            }

        }
        return text;
    }

    private void createChildLinearLayout(final RentVO vo, final int i) {
        View view = mInflater.inflate(R.layout.item_things_detail_horizontalscrollview,linear, false);
        SimpleDraweeView imgView = (SimpleDraweeView) view.findViewById(R.id.img_things_horizontalscrollview);
        imgView.setImageURI(vo.getImg());
        TextView text1 = (TextView) view.findViewById(R.id.text_things_horizontalscrollview_1);
        text1.setText(vo.getName());
        TextView text2 = (TextView) view.findViewById(R.id.text_things_horizontalscrollview_2);
        text2.setText("NT$ "+vo.getSaleprice()+"/萬");
        TextView text3 = (TextView) view.findViewById(R.id.text_things_horizontalscrollview_3);
        text3.setText("坪數:"+vo.getLawnarea()+" 坪");
        TextView text4 = (TextView) view.findViewById(R.id.text_things_horizontalscrollview_4);
        text4.setText("層樓:"+vo.getStorey());
        linear.addView(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String param ="?seq="+vo.getSeq();
                initDetailRequest(param);
                httpThingsModel.requestThings();
            }
        });
    }



}
